/*
 * @Author: licc
 * @Date: 2021-03-24 15:04:45
 * @Last Modified by: jinqiang
 * @Last Modified time: 2021-11-12 18:38:36
 */
<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="handleSearchFunc"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFunc">查询</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
        ref="table"
        :selection="limitArr.indexOf('system_message_setting_batch_enableOrDisable') > -1"
        :headers="tableHeaders"
        :data="messageTableData"
        :batchs="batchs"
        @batchClick="batchClick"
        :pagingData="pagingData"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.show && !['oprate', 'isEnable', 'type', 'role', 'queue'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'isEnable'"
              :key="index"
              :label="item.label"
              :width="68"
            >
              <template slot-scope="scope">
                <i class="V7_iconfont V7_iconV7tubiao_dian" :class="scope.row.isEnable === 'enable' ? 'enable-span':'disable-span'"></i>
                <span>{{scope.row.isEnable === 'enable'?'启用':'停用'}}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'type'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="100"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span>{{scope.row.typeStr}}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'role'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>{{scope.row.visibleRoleNameStr}}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'queue'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>{{scope.row.visibleQueueNameStr}}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="
                item.prop === 'oprate' && item.show
                && (limitArr.indexOf('system_message_setting_edit') > -1
                  || limitArr.indexOf('system_message_setting_enableOrDisable') > -1)
              "
              :key="index"
              :label="item.label"
              :width="75"
            >
              <template slot-scope="scope">
                <span
                  v-if="limitArr.indexOf('system_message_setting_edit') > -1"
                  class="oprate-span"
                  @click="handleEdit(scope.row)"
                >编辑</span>
                <span
                  v-if="limitArr.indexOf('system_message_setting_enableOrDisable') > -1"
                  class="oprate-span"
                  :class="scope.row.isEnable === 'disable'?'':'red-span'"
                  @click="handleEnableOrDisabled(scope.row)"
                >{{scope.row.isEnable === 'enable' ? '停用': '启用'}}</span>
                <!-- <span
                  v-if="limitArr.indexOf('customer_template_setting_delete') > -1"
                  class="oprate-span red-span"
                  @click="handleDel(scope.row)"
                >删除</span> -->
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <!-- #region 右侧抽屉 新增、编辑 -->
      <cuDrawer
        ref="cuDrawer"
        :drawerType="drawerType"
        :postForm="postForm"
        @handleConfirmEdit="handleConfirmEdit"
      ></cuDrawer>
      <!-- #endregion -->
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import cuDrawer from '@/views/message/systemMessage/addOrEditSysMsg.vue'
import configTable from '@/components/configCommon/table.vue'
import { deepClone, isHasFuncOrMenus } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { Store } from 'vuex/types/index'
import { MessageModule } from '@/store/modules/message/sysMsg'
interface DefaultForm {
  name: string
  type: string
  isEnable: string
  content: string
  contentTips: string
  level: any
  visiblePersonnel: any
  rules: string
  remindWay: any
}
interface PageData {
  total: number
  limit: number
  page: number
}
const defaultForm: DefaultForm = { // 新增、编辑 初始对象
  name: '', // 消息名称 disabled
  type: '', // 消息类型 disabled
  isEnable: '', // 是否开启
  content: '', // 消息内容
  contentTips: '', // 消息内容问号提示
  level: [], // 消息级别规则 disabled
  visiblePersonnel: { // 触达人员
    visibleRole: [], // 角色，id[]
    visibleQueue: [], // 技能组，工号[]
    visibleAgent: [] // 座席，id[]
  },
  rules: '', //  disabled
  remindWay: [] //  disabled
}
@Component({
  name: 'customerTemplateSetting',
  components: {
    QuickSearch,
    configTable,
    cuDrawer,
    continer
  }
})
export default class CustomerTemplateSetting extends Vue {
  // #region 基础数据
  [x: string]: any
  @Ref() private readonly table!: configTable
  @Ref() private readonly CustomerTemplateSetting!: cuDrawer
  private drawerType: string = 'add' // 新增 || 编辑
  private limitArr: any[] = [] // 权限控制
  private quickSearchForm: any = {} // 快捷搜索表单 需动态变化
  private listLoading: boolean = false
  private messageTableData = [] // list 数据
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private checkHeaders: [] = [] // 当前展示的表头信息
  private postForm = deepClone(defaultForm)
  private typeHeaderOptions = [ // 消息条目 状态
    { _id: '', name: '全部' },
    // { _id: 'system', name: '系统消息' },
    { _id: 'transmit', name: '传输中心' },
    { _id: 'notice', name: '公告管理' },
    { _id: 'mpNotice', name: '工单客户' },
    { _id: 'workorderNotice', name: '工单消息' },
    { _id: 'qualityCheck', name: '质检消息' }
  ]

  // #endregion

  // #region 页面全局函数
  // 初始化列表
  private initData () {
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    this.listLoading = true
    MessageModule.MessageCommonAction({ url: '/base/action/message/config/list', method: 'POST', data: actionData }).then(res => {
      if (res && res.success) {
        const list = res.list || []
        list.forEach((item: any) => {
          // 处理 消息类型
          const typeStr: any = this.typeHeaderOptions.find(v => v._id === item.type)
          item.typeStr = typeStr ? typeStr.name : ''
          // 处理 触达角色
          const visibleRoleNameArr: any = []
          if (item.visiblePersonnel && item.visiblePersonnel.visibleRole) {
            item.visiblePersonnel.visibleRole.forEach((user: any) => {
              const roleObj = (this.$store as Store<any>).state.common.publicCache.roleListObj[user]
              visibleRoleNameArr.push(roleObj ? `${roleObj.name}` : '—')
            })
          }
          item.visibleRoleNameStr = visibleRoleNameArr.join('、')
          // 处理 触达技能组
          const visibleQueueNameArr: any = []
          if (item.visiblePersonnel && item.visiblePersonnel.visibleRole) {
            item.visiblePersonnel.visibleQueue.forEach((queue: any) => {
              const queueObj = (this.$store as Store<any>).state.common.publicCache.queueListObj[queue]
              visibleQueueNameArr.push(queueObj ? `${queueObj.name}` : '—')
            })
          }
          item.visibleQueueNameStr = visibleQueueNameArr.join('、')
        })
        this.messageTableData = list
        this.pagingData.total = res.count || 0
      }
    }).finally(() => {
      this.listLoading = false
    })
  }
  // #endregion

  // #region 高级搜索相关
  // 查询
  private handleSearchFunc () {
    this.pagingData.page = 1
    this.initData()
  }
  // #endregion

  // #region 数据表格相关
  // header 表头
  private tableHeaders: object[] = [ // 标头配置信息
    { label: '消息名称', prop: 'name' },
    { label: '消息类型', prop: 'type' },
    { label: '消息状态', prop: 'isEnable' },
    { label: '触达角色', prop: 'role' },
    { label: '触达技能组', prop: 'queue' },
    { label: '更新时间', prop: 'updateTime', sortable: true },
    { label: '操作', prop: 'oprate' }
  ]

  // 启用、停用（批量启用、批量停用也走这里）
  private handleEnableOrDisabled (row: any) {
    this.$confirm(`确定要${row.isEnable === 'enable' ? '停用' : '启用'}【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionUrl = row.isEnable === 'enable' ? '/base/action/message/config/disable' : '/base/action/message/config/enable'
      const data: any = {}
      if (row.isAll) { // 如果是全选
        data.condition = this.quickSearchForm.form
      } else {
        data.ids = row.ids ? row.ids : [row._id]
      }
      MessageModule.MessageCommonAction({
        url: actionUrl,
        method: 'POST',
        data
      }).then((res: any) => {
        if (res && res.success) {
          const str = row.isEnable === 'enable' ? `停用【${row.name}】成功` : `启用【${row.name}】成功`
          this.$message({ message: str, type: 'success' })
          this.initData()
        }
      }).catch((e) => {
        console.log(e)
      })
    })
  }

  // operate 编辑某行
  private handleEdit (row: any) {
    this.postForm = deepClone(row);
    this.drawerType = 'edit';
    (this as any).$refs.cuDrawer.openOrCloseDraw()
  }

  // 编辑某行 确认按钮
  private handleConfirmEdit (form) {
    const pF: any = JSON.parse(JSON.stringify(form, ['_id', 'content', 'remindWay']))
    pF.visiblePersonnel = deepClone(form.visiblePersonnel)
    // console.log('======= edit pF:', pF);
    MessageModule.MessageCommonAction({ url: '/base/action/message/config/update', method: 'POST', data: pF }).then(res => {
      if (res && res.success) {
        (this as any).$refs.cuDrawer.closeDraw()
        this.$message.success('消息条目编辑成功')
        this.initData()
      }
    }).finally(() => {
      (this as any).$refs.cuDrawer.closeDraw()
    })
  }

  // operate 删除某行
  private handleDel (row: any) {
    this.$confirm('该操作将删除该消息条目及配置的所有信息，是否确认？', '确认删除消息条目', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.listLoading = true
      MessageModule.MessageCommonAction({ url: '/base/action/message/config/del', method: 'POST', data: { ids: [row._id] } }).then(res => {
        if (res && res.success) {
          this.$message.success('消息条目删除成功')
          this.handleSearchFunc()
        }
      }).finally(() => {
        this.listLoading = false
      })
    }).catch(e => {
      console.log(e)
    })
  }

  // 更改表头
  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  // 改变每页行数大小
  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  // 翻页
  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.initData()
  }

  // 批量操作
  private batchs: any = [
    {
      name: '批量启用',
      action: 'enable'
    },
    {
      name: '批量停用',
      action: 'disable'
    }
  ]

  // 批量操作的回调
  private batchClick (action: string, selectList: any) {
    const row: any = {
      isEnable: action === 'enable' ? 'disable' : 'enable'
    }
    if (selectList === true) { // 如果是全选
      row.isAll = true
      row.name = '全部消息'
    } else {
      row.ids = selectList
      row.name = '所选消息'
    }
    switch (action) {
      case 'enable':
        this.handleEnableOrDisabled(row)
        break
      case 'disable':
        this.handleEnableOrDisabled(row)
        break
    }
  }
  // #endregion

  // #region 生命周期钩子
  private beforeMount () {
    this.limitArr = []
    const arr = [
      'system_message_setting_edit',
      'system_message_setting_enableOrDisable',
      'system_message_setting_batch_enableOrDisable'
    ]
    // 新增，停用/启用， 编辑，配置，删除
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, false)) {
        this.limitArr.push(item)
      }
    })
  }

  private mounted () {
    this.$getCache('/base/action/general/cache/query', ['roleList', 'queueList', 'userList'], true).then((data: any) => {
      this.quickSearchForm = { // 高级搜索数据
        form: {
          name: '',
          agentNumber: '',
          type: '',
          role: '',
          queue: ''
        },
        advSearchOptions: [ // 高级搜索数据
          { label: '消息名称', name: 'name', inputType: 'input', clearable: true, placeholder: '请输入消息名称' },
          { label: '触达工号', name: 'agentNumber', inputType: 'input', clearable: true, placeholder: '请输入触达工号' },
          { label: '消息类型', name: 'type', inputType: 'select', clearable: true, selectData: this.typeHeaderOptions, placeholder: '请选择' },
          { label: '触达角色', name: 'role', inputType: 'select', clearable: true, selectData: CommonModule.publicCache.roleList, placeholder: '请选择' },
          { label: '触达技能组', name: 'queue', inputType: 'select', clearable: true, selectData: CommonModule.publicCache.queueList, placeholder: '请选择' }
        ]
      }
      this.$nextTick(() => {
        this.handleSearchFunc()
      })
    })
  }

  private beforeRouteLeave (to: any, from: any, next: any) {
    this.$nextTick(() => {
      (this as any).$refs.cuDrawer.closeDraw()
    })
    next()
  }
  // #endregion
}
</script>
<style lang="stylus" scoped>
  .oprate-span
    cursor pointer
    color $c-main
    margin 0 4px
  .red-span,.disable-span
    color $c-danger
  .enable-span
    color $c-green
  .disable-span,.enable-span
    font-size 12px
</style>
